#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QStringList>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
#include <QStandardPaths>
#include <QFileDialog>
#include <QMessageBox>
#include <QProcess>
#include <QTime>
#include <QPixmap>
#include <QRegExp>
#include <QScreen>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    move(qApp->primaryScreen()->geometry().center() - geometry().center());
    this->setWindowTitle(QApplication::applicationName());
    this->setWindowIcon(QIcon(":/logo.ico"));

    dataLocation = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);
    m_size = 0;
    send_count=0;
    statusLabel = new QLabel;
    statusLb2 = new QLabel;
    aboutForm = new FormAbout;

    DefaultDisplay();

    eThread = new extractThread;
    pThread = new PrbThread;
    connect(ui->actionabout,&QAction::triggered,this,&MainWindow::showAbout);

    connect(this,&MainWindow::starting,eThread,&extractThread::recvFileName);
    connect(eThread,&extractThread::sendStatus,this,[=](bool status){
        unPackFlag = status;
        if(unPackFlag){
            QRegExp re(".png|.svg");
            QDir iconDir(TMPFILEPATH);
            QFileInfoList flist = iconDir.entryInfoList();
            foreach (QFileInfo i, flist) {
                qint8 flag = re.indexIn(i.fileName());
                if(flag!=-1){
                    iconName = i.fileName();
                    break;
                }
                else
                {
                    iconName = "";
                }
            }
            SetFileIcon(TMPFILEPATH+iconName);
        }
        ui->toolButton->setText(filePath);
        ui->nextBtn->setEnabled(true);
        ui->toolButton->setEnabled(true);
        setStatusBar("当前文件: "+filePath,"complete!");
    });
    connect(eThread,&extractThread::sendData,this,[=](int maxSize){
        max_size = maxSize;

    });

    connect(this,&MainWindow::startingCopy,pThread,&PrbThread::recvPath);
    connect(pThread,&PrbThread::sendFileInfo,this,[=](QFileInfo fileN_){
        nameList.push_back(fileN_.fileName());
        if(send_count<5000||send_count%5000==0)
        {
            ui->listWidget->insertItems(0,nameList);
            nameList.clear();
        }
        send_count++;
        ui->mCount->setText(QString::number(send_count));
        m_size+=fileN_.size();
        ui->progressBar->setValue(m_size);
    });

    connect(pThread,&PrbThread::sendStatus,this,[=](bool status)
    {
        if(status)
        {
            nameList.clear();
            send_count=0;
            m_size=0;
            QMessageBox::information(this,"提示","完美结束,现在可以退出该软件啦",QMessageBox::Ok);
            setStatusBar("","complete!");
        }
        else
            QMessageBox::information(this,"错误","遭遇错误,可自行前往"+savePath+"检查\n造成错误的原因有可能是路径没有权限,请选择用户目录进行解压",QMessageBox::Ok);
    });

}

MainWindow::~MainWindow()
{
    delete ui;
}

//初始化
void MainWindow::DefaultDisplay()
{
    setStatusBar("请选择文件");
    for(int i=1;i<=3;i++)
    {
        ui->tabWidget->setTabEnabled(i,false);
    }
    ui->tabWidget->setStyleSheet("QTabBar::tab:disabled {width: 0; color: transparent;}");
    ui->lastBtn->setEnabled(false);
    ui->nextBtn->setEnabled(false);

}

void MainWindow::SetFileIcon(const QString &str)
{
    ui->toolButton->setIcon(QIcon(str));
}

//设置step2页
void MainWindow::setSep2(const QString &path_)
{
    //Icon
    QRegExp re(".png|.svg");
    QDir iconDir(path_);
    QFileInfoList flist = iconDir.entryInfoList();
    foreach (QFileInfo i, flist) {
        qint8 flag = re.indexIn(i.fileName());
        if(flag!=-1){
            iconName = i.fileName();
        }
    }

    ui->toolButton_2->setIconSize(ui->toolButton_2->size());
    ui->toolButton_2->setIcon(QIcon(path_+iconName));
    //desciption
    QFileSystemModel* model_ = new QFileSystemModel;
    model_->setRootPath(path_);
    ui->columnView->setModel(model_);
    ui->columnView->setRootIndex(model_->index(path_));

    ui->nameLabel->setText(fileName);
    ui->typeLabel->setText(fileType);
    ui->dateLabel->setText(fileDate);
    setSize(fileSize);
    ui->pathLabel->setText(filePath);

}

void MainWindow::setSep3(const QString &path_)
{
    deleteStatus = ui->deleteRadio->isChecked();
    addLaunchStatus = ui->addLaunchRadio->isChecked();
    addDeskStatus = ui->addDeskRadio->isChecked();
    savePath = ui->filePath->text();

    if(deleteStatus)
    {
        ui->infoList->addItem("删除源文件"+QFileInfo(path_).fileName());
    }

    if(addLaunchStatus)
    {
        ui->infoList->addItem("将添加快捷方式至启动器");
    }

    if(addDeskStatus)
    {
        ui->infoList->addItem("将添加快捷方式至桌面");
    }
    ui->infoList->addItem("将解压文件至目录:"+savePath);
}

//文件信息
void MainWindow::getFileInfo(const QString &path_)
{
    QFileInfo fileInfo(path_);
    fileName = fileInfo.completeBaseName().replace(" ","");
    fileType = fileInfo.suffix();
    fileDate = fileInfo.metadataChangeTime().toString("yyyy-MM-dd ddd hh:mm:ss");
    fileSize = QString::number(fileInfo.size());

}

void MainWindow::setSize(const QString &size)
{
    if(size.toDouble()<1024)
    {
        ui->sizeLabel->setText(size+" b");
    }
    else if(1024<=size.toDouble()&&size.toDouble()<1024*1024)
    {
        ui->sizeLabel->setText(QString::number(size.toDouble()/1024,'f',2)+" kb");
    }
    else if(1024*1024<=size.toDouble()&&size.toDouble()<1024*1024*1024)
    {
        ui->sizeLabel->setText(QString::number(size.toDouble()/1024/1024,'f',2)+" MB");
    }
    else
    {
        ui->sizeLabel->setText(QString::number(size.toDouble()/1024/1024/1024,'f',2)+"GB");
    }

}


bool MainWindow::finishedUnpack()
{
    ui->mCount->setText("0");
    ui->progressBar->setValue(0);
    QString sourcePath = QStandardPaths::writableLocation(QStandardPaths::TempLocation)+"/squashfs-root";
    emit startingCopy(sourcePath,savePath);
    pThread->start();

    if(deleteStatus)
    {
        QFileInfo file(filePath);
        if(file.isFile())
        {
            if(QDir().remove(filePath))
            {
                ui->listWidget->addItem("文件"+file.fileName()+"已删除");
                qDebug()<<"删除成功";
            }
            else
            {
                QMessageBox::information(this,"错误","源文件删除失败,请检查",QMessageBox::Ok);
            }
        }
        else
            QMessageBox::information(this,"错误","源文件删除失败,不存在文件",QMessageBox::Ok);
    }

    QStringList strList;
    QString deskFPath(dataLocation+"/"+fileName+"/AppRun");
    QString deskIPath(dataLocation+"/"+fileName+"/"+iconName);
    strList<<"[Desktop Entry]"<<"Exec="+deskFPath<<"Icon="+deskIPath\
          <<"Name="+fileName<<"Terminal=false"<<"Type=Application";
    QDir deskDir(QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation));
    if(!deskDir.exists())
    {
        if(!QDir().mkdir(deskDir.absolutePath()))
        {
            return false;
        }
    }
    QFile file(QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation)+"/"+fileName+".desktop");


    if(!file.open(QIODevice::WriteOnly|QIODevice::Text))
    {
        return false;
    }

    QTextStream desktopFile(&file);
    if(addLaunchStatus||addDeskStatus)
    {
        foreach (QString i, strList) {
            desktopFile<<i+"\n";
            desktopFile.flush();
        }
        if(addDeskStatus)
        {
            file.copy(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)+"/"+fileName+".desktop");
        }
    }

    file.close();
    return true;
}

//状态栏
void MainWindow::setStatusBar(const QString &s,const QString &t)
{
    statusLabel->setMinimumSize(statusLabel->sizeHint());
    statusLabel->setAlignment(Qt::AlignLeft);
    statusLabel->setText(s);
    ui->statusbar->addWidget(statusLabel);

    statusLb2->setText(t);
    statusLb2->setAlignment(Qt::AlignRight);
    ui->statusbar->addPermanentWidget(statusLb2);
}

//下一页按钮
void MainWindow::on_nextBtn_clicked()
{
    int index = ui->tabWidget->currentIndex();
    ui->tabWidget->setTabEnabled(index+1,true);
    ui->tabWidget->setStyleSheet("QTabBar::tab:disabled {width: 0; color: transparent;}");
    ui->tabWidget->setCurrentIndex(index+1);
}

//上一页按钮
void MainWindow::on_lastBtn_clicked()
{
    int index = ui->tabWidget->currentIndex();
    ui->tabWidget->setCurrentIndex(index-1);
}

//step1选择文件
void MainWindow::on_toolButton_clicked()
{
    filePath = QFileDialog::getOpenFileName(this,"选择文件",QDir::homePath(),"*.appimage");

    if(filePath.length()==0){
        return;
    }

    getFileInfo(filePath);
    ui->toolButton->setText("请稍等,进程进行中...\n\n图标即将显示...\n\n已选中文件:\n"+filePath);
    ui->filePath->setText(dataLocation+"/"+fileName);
    setStatusBar("当前文件: "+filePath,"正在预解压...");
    //调用子进程

    emit starting(filePath);
    eThread->start();
    ui->toolButton->setEnabled(false);
}


//finished
void MainWindow::on_pushButton_clicked()
{
    finishedUnpack();
}

void MainWindow::on_selectPath_clicked()
{
    QString saveFile = QFileDialog::getExistingDirectory(this,"保存位置",QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation));
    ui->filePath->setText(saveFile+"/"+fileName);
}

void MainWindow::on_tabWidget_currentChanged(int index)
{
    switch (index) {
    case 0:
        ui->lastBtn->setEnabled(false);
        ui->nextBtn->setEnabled(true);
        setStatusBar("当前文件: "+filePath);
        break;
    case 1:
        ui->lastBtn->setEnabled(true);
        ui->nextBtn->setEnabled(true);
        setStatusBar("当前文件: "+filePath,"可点击路径预览...点击下一步继续");

        setSep2(TMPFILEPATH);
        break;
    case 2:
        ui->lastBtn->setEnabled(true);
        ui->nextBtn->setEnabled(true);
        setStatusBar("当前文件: "+filePath,"将解压保存至:"+ui->filePath->text());
        break;
    case 3:
        ui->lastBtn->setEnabled(true);
        ui->nextBtn->setEnabled(false);
        setStatusBar("当前文件: "+filePath,"点击开始完成最后一步吧");

        ui->infoList->clear();
        setSep3(dataLocation);
        ui->progressBar->setMaximum(max_size);
        ui->listWidget->clear();

        break;
    default:
        break;
    }
}

void MainWindow::showAbout()
{
    aboutForm->move(this->geometry().center() - aboutForm->geometry().center());
//    aboutForm->move(this->window()->x()+(this->window()->width()-aboutForm->width())/2,this->window()->y()+(this->window()->height()-aboutForm->height())/2);
    aboutForm->show();
}
